package arrowandsphere;

import java.io.*;
import java.net.*;
import java.util.*;

public class SessionAppThread extends Thread {
    Socket s;
        
    public SessionAppThread(Socket s) {
        this.s = s;
    }
        
    @Override
    public void run() {
        System.out.println("Thread for " + s + " started.");
        try {
            ObjectOutputStream oos = new ObjectOutputStream(s.getOutputStream());
            ObjectInputStream ois = new ObjectInputStream(s.getInputStream());
            while (true) {
                System.out.println("Waiting for requests from " + s);
                Object o = ois.readObject();
                System.out.println("Request received from " + s);
                if (o instanceof CreateSession) {
                    SessionApp.createSession((CreateSession)o);
                }
                else if (o instanceof ReadSession) {
                    Session session = SessionApp.readSession((ReadSession)o);
                    oos.writeObject(session);
                    oos.flush();
                }
                else if (o instanceof ReadSessions) {
                    List<Session> sessions = SessionApp.readSessions((ReadSessions)o);
                    oos.writeObject(sessions);
                    oos.flush();
                }
                else if (o instanceof UpdateSession) {
                    SessionApp.updateSession((UpdateSession)o);
                }
                else if (o instanceof DeleteSession) {
                    SessionApp.deleteSession((DeleteSession)o);
                }
            }
        } catch (Exception e) {
            System.out.println("Thread for " + s + " caught the following exception: " + e);
        }
    }
}
